package com.mulong.mall.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mulong.common.dao.mall.BrandDao;
import com.mulong.common.dao.mall.DeliveryDao;
import com.mulong.common.domain.pojo.mall.custom.BrandQuery;
import com.mulong.common.domain.pojo.mall.custom.CustomSupplierChannelDeliveryCharge;
import com.mulong.common.domain.pojo.mall.custom.DeliveryTypeQuery;
import com.mulong.common.domain.pojo.mall.custom.SupplierChannelDeliveryChargeQuery;
import com.mulong.common.enums.Province;
import com.mulong.common.exception.ErrorEnums;
import com.mulong.common.exception.MulongException;
import com.mulong.common.manager.BusinessManager;
import com.mulong.mall.constants.Constants;
import com.mulong.mall.domain.bo.manager.*;
import com.mulong.mall.domain.param.manager.*;
import com.mulong.mall.domain.result.manager.*;
import com.mulong.mall.service.ManagerBusinessService;
import com.mulong.mall.util.MallRequestContext;

import lombok.extern.slf4j.Slf4j;

/**
 * ManagerBusinessServiceImpl
 * 
 * @author mulong
 * @data 2021-06-21 14:03:52
 */
@Slf4j
@Service
public class ManagerBusinessServiceImpl implements ManagerBusinessService {
    @Autowired
    private DeliveryDao deliveryDao;
    @Autowired
    private BrandDao brandDao;
    @Autowired
    private BusinessManager businessManager;

    /**
     * 查询快递方式
     * 
     * @author mulong
     */
    @Override
    public GetDeliveryTypeByPageResult getDeliveryTypeByPage(GetDeliveryTypeByPageParam param) {
        DeliveryTypeQuery query = new DeliveryTypeQuery();
        query.setNameKeyword(param.getNameKeyword());
        query.setOrderBy("`delivery_type_order` ASC");
        int pageNo = param.getPageNo() == null ? Constants.DEFAULT_PAGE_NO : param.getPageNo();
        int pageSize = param.getPageSize() == null ? Constants.DEFAULT_PAGE_SIZE : param.getPageSize();
        PageHelper.startPage(pageNo, pageSize, true);
        Page<com.mulong.common.domain.pojo.mall.DeliveryType> page = (Page<com.mulong.common.domain.pojo.mall.DeliveryType>) deliveryDao.queryDeliveryType(query);
        GetDeliveryTypeByPageResult getDeliveryTypeByPageResult = new GetDeliveryTypeByPageResult(page.getPageNum(), page.getPageSize(), (int)page.getTotal());
        List<com.mulong.common.domain.pojo.mall.DeliveryType> list = page.getResult();
        if (!CollectionUtils.isEmpty(list)) {
            getDeliveryTypeByPageResult.setResult(list.stream().map(DeliveryType::new).collect(Collectors.toList()));
        }
        return getDeliveryTypeByPageResult;
    }

    /**
     * 添加快递方式
     * 
     * @author mulong 
     */
    @Override
    public DeliveryType addDeliveryType(DeliveryType deliveryType) {
        deliveryType.setId(null);
        com.mulong.common.domain.pojo.mall.DeliveryType newRecord = deliveryType.buildDeliveryType();
        newRecord = deliveryDao.addDeliveryType(newRecord, MallRequestContext.getUsername());
        return new DeliveryType(newRecord);
    }

    /**
     * 查询快递方式
     * 
     * @author mulong 
     */
    @Override
    public DeliveryType getDeliveryTypeById(Integer id) {
        com.mulong.common.domain.pojo.mall.DeliveryType record = deliveryDao.queryDeliveryTypeById(id);
        if (record == null) {
            throw new MulongException(ErrorEnums.RESOURCE_NOT_EXISTS);
        }
        return new DeliveryType(record);
    }

    /**
     * 更新快递方式
     * 
     * @author mulong 
     */
    @Override
    public DeliveryType putDeliveryTypeById(Integer id, DeliveryType deliveryType) {
        if (!id.equals(deliveryType.getId())) {
            log.error("id mismatch");
            throw new MulongException(ErrorEnums.ILLEGAL_PARAM);
        }
        com.mulong.common.domain.pojo.mall.DeliveryType record = deliveryDao.queryDeliveryTypeById(id);
        if (record == null) {
            throw new MulongException(ErrorEnums.RESOURCE_NOT_EXISTS);
        }
        com.mulong.common.domain.pojo.mall.DeliveryType newRecord = deliveryType.buildDeliveryType();
        record.setName(newRecord.getName());
        record.setDescription(newRecord.getDescription());
        record.setDeliveryTypeOrder(newRecord.getDeliveryTypeOrder());
        deliveryDao.putDeliveryType(record, MallRequestContext.getUsername());
        return new DeliveryType(record);
    }

    /**
     * 删除快递方式
     * 
     * @author mulong 
     */
    @Override
    public DeliveryType deleteDeliveryTypeById(Integer id) {
        com.mulong.common.domain.pojo.mall.DeliveryType record = deliveryDao.queryDeliveryTypeById(id);
        if (record == null) {
            throw new MulongException(ErrorEnums.RESOURCE_NOT_EXISTS);
        }
        deliveryDao.deleteDeliveryType(record, MallRequestContext.getUsername());
        return new DeliveryType(record);
    }

    /**
     * 查询邮费
     * 
     * @author mulong
     */
    public GetDeliveryChargeByPageResult getDeliveryChargeByPage(GetDeliveryChargeByPageParam param) {
        SupplierChannelDeliveryChargeQuery query = new SupplierChannelDeliveryChargeQuery();
        query.setDeliveryTypeId(param.getDeliveryTypeId());
        query.setProvince(param.getProvince());
        query.setOrderBy("scdc.`update_time` DESC");
        int pageNo = param.getPageNo() == null ? Constants.DEFAULT_PAGE_NO : param.getPageNo();
        int pageSize = param.getPageSize() == null ? Constants.DEFAULT_PAGE_SIZE : param.getPageSize();
        PageHelper.startPage(pageNo, pageSize, true);
        Page<CustomSupplierChannelDeliveryCharge> page = (Page<CustomSupplierChannelDeliveryCharge>) deliveryDao.queryDeliveryCharge(query);
        GetDeliveryChargeByPageResult getDeliveryChargeByPageResult = new GetDeliveryChargeByPageResult(page.getPageNum(), page.getPageSize(), (int)page.getTotal());
        List<CustomSupplierChannelDeliveryCharge> list = page.getResult();
        if (!CollectionUtils.isEmpty(list)) {
            getDeliveryChargeByPageResult.setResult(list.stream().map(DeliveryCharge::new).collect(Collectors.toList()));
        }
        return getDeliveryChargeByPageResult;
    }

    /**
     * 添加邮费
     * 
     * @author mulong 
     */
    public DeliveryCharge addDeliveryCharge(DeliveryCharge deliveryCharge) {
        deliveryCharge.setId(null);
        com.mulong.common.domain.pojo.mall.SupplierChannelDeliveryCharge newRecord = deliveryCharge.buildSupplierChannelDeliveryCharge();
        newRecord = deliveryDao.addDeliveryCharge(newRecord, MallRequestContext.getUsername());
        return new DeliveryCharge(newRecord);
    }

    /**
     * 查询邮费
     * 
     * @author mulong 
     */
    public DeliveryCharge getDeliveryChargeById(Long id) {
        com.mulong.common.domain.pojo.mall.SupplierChannelDeliveryCharge record = deliveryDao.queryDeliveryChargeById(id);
        if (record == null) {
            throw new MulongException(ErrorEnums.RESOURCE_NOT_EXISTS);
        }
        return new DeliveryCharge(record);
    }

    /**
     * 更新邮费
     * 
     * @author mulong 
     */
    public DeliveryCharge putDeliveryChargeById(Long id, DeliveryCharge deliveryCharge) {
        if (!id.equals(deliveryCharge.getId())) {
            log.error("id mismatch");
            throw new MulongException(ErrorEnums.ILLEGAL_PARAM);
        }
        com.mulong.common.domain.pojo.mall.SupplierChannelDeliveryCharge record = deliveryDao.queryDeliveryChargeById(id);
        if (record == null) {
            throw new MulongException(ErrorEnums.RESOURCE_NOT_EXISTS);
        }
        com.mulong.common.domain.pojo.mall.SupplierChannelDeliveryCharge newRecord = deliveryCharge.buildSupplierChannelDeliveryCharge();
        record.setChannelId(newRecord.getChannelId());
        record.setDeliveryTypeId(newRecord.getDeliveryTypeId());
        record.setProvince(newRecord.getProvince());
        record.setFirstPrice(newRecord.getFirstPrice());
        record.setAddPrice(newRecord.getAddPrice());
        deliveryDao.putDeliveryCharge(record, MallRequestContext.getUsername());
        return new DeliveryCharge(record);
    }

    /**
     * 删除邮费
     * 
     * @author mulong 
     */
    public DeliveryCharge deleteDeliveryChargeById(Long id) {
        com.mulong.common.domain.pojo.mall.SupplierChannelDeliveryCharge record = deliveryDao.queryDeliveryChargeById(id);
        if (record == null) {
            throw new MulongException(ErrorEnums.RESOURCE_NOT_EXISTS);
        }
        deliveryDao.deleteDeliveryCharge(record, MallRequestContext.getUsername());
        return new DeliveryCharge(record);
    }

    /**
     * 批量添加邮费
     * 
     * @author mulong 
     */
    public AddBatchDeliveryChargeResult addBatchDeliveryCharge(AddBatchDeliveryChargeParam param) {
        List<Province> provinceList = new ArrayList<>();
        for (String item : param.getProvinces()) {
            Province province = Province.getByCode(item);
            if (province == null) {
                province = Province.getByName(item);
            }
            if (province == null) {
                String msg = "未识别的省份名称:" + item;
                throw new MulongException(ErrorEnums.HANDLE_FAILED_TEMPLETE.format(msg));
            }
            provinceList.add(province);
        }
        BigDecimal firstPrice = param.getFirstPrice();
        BigDecimal addPrice = param.getAddPrice();
        for (Integer item : param.getDeliveryTypeIds()) {
            businessManager.addSupplierChannelDeliveryCharge(item, provinceList, firstPrice, addPrice, MallRequestContext.getUsername());
        }
        int count = provinceList.size() * param.getDeliveryTypeIds().size();
        AddBatchDeliveryChargeResult result = new AddBatchDeliveryChargeResult();
        result.setCount(count);
        return result;
    }

    /**
     * 查询品牌
     * 
     * @author mulong
     */
    @Override
    public GetBrandByPageResult getBrandByPage(GetBrandByPageParam param) {
        BrandQuery query = new BrandQuery();
        query.setNameKeyword(param.getNameKeyword());
        query.setOrderBy("`brand_order` ASC");
        int pageNo = param.getPageNo() == null ? Constants.DEFAULT_PAGE_NO : param.getPageNo();
        int pageSize = param.getPageSize() == null ? Constants.DEFAULT_PAGE_SIZE : param.getPageSize();
        PageHelper.startPage(pageNo, pageSize, true);
        Page<com.mulong.common.domain.pojo.mall.Brand> page = (Page<com.mulong.common.domain.pojo.mall.Brand>) brandDao.query(query);
        GetBrandByPageResult getBrandByPageResult = new GetBrandByPageResult(page.getPageNum(), page.getPageSize(), (int)page.getTotal());
        List<com.mulong.common.domain.pojo.mall.Brand> list = page.getResult();
        if (!CollectionUtils.isEmpty(list)) {
            getBrandByPageResult.setResult(list.stream().map(Brand::new).collect(Collectors.toList()));
        }
        return getBrandByPageResult;
    }

    /**
     * 添加品牌
     * 
     * @author mulong 
     */
    @Override
    public Brand addBrand(Brand brand) {
        brand.setId(null);
        com.mulong.common.domain.pojo.mall.Brand newRecord = brand.buildBrand();
        newRecord = brandDao.add(newRecord, MallRequestContext.getUsername());
        return new Brand(newRecord);
    }

    /**
     * 查询品牌
     * 
     * @author mulong 
     */
    @Override
    public Brand getBrandById(Integer id) {
        com.mulong.common.domain.pojo.mall.Brand record = brandDao.queryById(id);
        if (record == null) {
            throw new MulongException(ErrorEnums.RESOURCE_NOT_EXISTS);
        }
        return new Brand(record);
    }

    /**
     * 更新品牌
     * 
     * @author mulong 
     */
    @Override
    public Brand putBrandById(Integer id, Brand brand) {
        if (!id.equals(brand.getId())) {
            log.error("id mismatch");
            throw new MulongException(ErrorEnums.ILLEGAL_PARAM);
        }
        com.mulong.common.domain.pojo.mall.Brand record = brandDao.queryById(id);
        if (record == null) {
            throw new MulongException(ErrorEnums.RESOURCE_NOT_EXISTS);
        }
        com.mulong.common.domain.pojo.mall.Brand newRecord = brand.buildBrand();
        record.setName(newRecord.getName());
        record.setShortName(newRecord.getShortName());
        record.setBrandOrder(newRecord.getBrandOrder());
        record.setDescription(newRecord.getDescription());
        brandDao.put(record, MallRequestContext.getUsername());
        return new Brand(record);
    }

    /**
     * 删除品牌
     * 
     * @author mulong 
     */
    @Override
    public Brand deleteBrandById(Integer id) {
        com.mulong.common.domain.pojo.mall.Brand record = brandDao.queryById(id);
        if (record == null) {
            throw new MulongException(ErrorEnums.RESOURCE_NOT_EXISTS);
        }
        brandDao.delete(record, MallRequestContext.getUsername());
        return new Brand(record);
    }

}
